import React, { useState, useEffect, useRef } from 'react'
import Header from '../components/Header'
import { chatQuery, getChatHistory, searchChatHistory, deleteChatConversation, clearChatHistory } from '../utils/api'
import '../styles/theme.css'
import '../styles/backgrounds.css'
import './Chat.css'

export default function Chat(){
  const [expandedSections, setExpandedSections] = useState({ 
    possibilities: true, 
    checks: false, 
    uploadChecklist: false, 
    searchKeywords: false 
  })

  function mapConfidenceToRisk(conf) {
    if (conf == null) return { label: '未知', color: '#999' }
    if (typeof conf === 'string') {
      const m = conf.match(/(\d{1,3})%/)
      if (m) {
        const p = Number(m[1]) / 100
        conf = p
      } else if (/高|中|低/.test(conf)) {
        if (/高/.test(conf)) return { label: '高', color: '#ef4444' }
        if (/中/.test(conf)) return { label: '中', color: '#f59e0b' }
        if (/低/.test(conf)) return { label: '低', color: '#10b981' }
      }
    }
    if (typeof conf === 'number') {
      if (conf >= 0.8) return { label: '高', color: '#ef4444' }
      if (conf >= 0.6) return { label: '中', color: '#f59e0b' }
      return { label: '低', color: '#10b981' }
    }
    return { label: '未知', color: '#999' }
  }

  const [messages, setMessages] = useState([
    { from:'bot', text:'👋 您好！我是 AI 智能助手，可以帮您：\n\n✨ 自然语言检索图片\n🔍 分析缺陷类型\n💡 提供专业建议\n🧠 记住对话历史，智能上下文理解\n\n试试输入："查找裂纹" 或 "显示所有油污图片"' }
  ])
  const [input, setInput] = useState('')
  const [loading, setLoading] = useState(false)
  const [chatOnly, setChatOnly] = useState(false)
  const [isTyping, setIsTyping] = useState(false)
  const [historyList, setHistoryList] = useState([])
  const [historySearchQuery, setHistorySearchQuery] = useState('')
  const [historyLoading, setHistoryLoading] = useState(false)
  const [showSidebar, setShowSidebar] = useState(true)
  const [currentConversationId, setCurrentConversationId] = useState(null)
  const [historyPage, setHistoryPage] = useState(1)
  const [hasMoreHistory, setHasMoreHistory] = useState(true)
  const [dateFilter, setDateFilter] = useState('all')
  const scrollRef = useRef()
  const inputRef = useRef()

  useEffect(()=>{ 
    if(scrollRef.current) {
      scrollRef.current.scrollTo({
        top: scrollRef.current.scrollHeight,
        behavior: 'smooth'
      })
    }
  }, [messages, isTyping])

  function push(msg){ 
    setMessages(prev => [...prev, msg]) 
  }

  async function onSend(){
    const text = input.trim()
    if(!text || loading) return
    
    push({ from:'user', text })
    setInput('')
    setLoading(true)
    setIsTyping(true)
    
    try{
      const { text: replyText, results, structured } = await chatQuery(text, { chatOnly })
      
      // 模拟打字延迟
      await new Promise(r => setTimeout(r, 300))
      setIsTyping(false)
      
      const displayText = chatOnly ? (replyText || '').replace(/图片名称[:：][\s\S]*$/u, '').trim() : replyText
      push({ from: 'bot', text: displayText })

      if (structured) {
        push({ from: 'bot', structured })
      }

      if (!chatOnly && results && results.length > 0) {
        push({ from: 'bot', images: results.slice(0, 6) })
      }
    }catch(err){
      setIsTyping(false)
      push({ from:'bot', text: `❌ 出错：${err.message || err}`, error: true })
    }finally{
      setLoading(false)
      if (inputRef.current) inputRef.current.focus()
    }
  }

  function handleKeyPress(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      onSend()
    }
  }

  // 加载历史记录（支持分页）
  async function loadHistory(append = false) {
    setHistoryLoading(true)
    try {
      const limit = 20
      const page = append ? historyPage : 1
      
      console.log(`📜 [前端] 请求历史记录 - 追加模式: ${append}, 页码: ${page}, 筛选: ${dateFilter}`)
      
      const result = await getChatHistory(limit, page, dateFilter)
      
      console.log(`📡 [前端] API 返回:`, result)
      
      const conversations = result?.conversations || []
      const hasMore = result?.hasMore !== false
      
      console.log(`📊 [前端] 解析结果 - 对话数: ${conversations.length}, 还有更多: ${hasMore}`)
      
      if (append) {
        // 追加模式：添加到现有列表
        setHistoryList(prev => {
          const newList = [...prev, ...conversations]
          console.log(`✅ [前端] 追加后总数: ${newList.length}`)
          return newList
        })
        setHistoryPage(page + 1)
      } else {
        // 刷新模式：替换整个列表
        setHistoryList(conversations)
        setHistoryPage(2)
        console.log(`✅ [前端] 刷新后显示: ${conversations.length} 条`)
      }
      
      setHasMoreHistory(hasMore)
      
    } catch (err) {
      console.error('❌ [前端] 加载历史记录失败:', err)
      setHistoryList([])
      setHasMoreHistory(false)
    } finally {
      setHistoryLoading(false)
    }
  }

  // 加载更多历史记录
  function loadMoreHistory() {
    if (!historyLoading && hasMoreHistory) {
      loadHistory(true)
    }
  }

  // 日期筛选变化
  function handleDateFilterChange(filter) {
    console.log(`🔍 [前端] 切换日期筛选为: ${filter}`)
    setDateFilter(filter)
    setHistoryPage(1)
    setHistorySearchQuery('') // 清空搜索查询
    // 不需要手动调用 loadHistory，useEffect 会自动触发
  }

  // 搜索历史记录
  async function handleHistorySearch() {
    if (!historySearchQuery.trim()) {
      // 如果搜索为空，重新加载历史记录（使用当前的日期筛选）
      loadHistory(false)
      return
    }
    
    console.log(`🔍 [前端] 执行搜索: "${historySearchQuery}"`)
    setHistoryLoading(true)
    try {
      // 搜索时不使用日期筛选
      const { conversations } = await searchChatHistory(historySearchQuery, 20)
      setHistoryList(conversations || [])
      setHasMoreHistory(false) // 搜索结果不分页
      console.log(`✅ [前端] 搜索返回 ${conversations?.length || 0} 条结果`)
    } catch (err) {
      console.error('❌ [前端] 搜索历史失败:', err)
      setHistoryList([])
    } finally {
      setHistoryLoading(false)
    }
  }

  // 删除单条历史
  async function handleDeleteHistory(id) {
    if (!confirm('确定删除这条对话记录吗？')) return
    try {
      await deleteChatConversation(id)
      setHistoryList(prev => prev.filter(h => h.id !== id))
    } catch (err) {
      alert('删除失败: ' + err.message)
    }
  }

  // 清空所有历史
  async function handleClearHistory() {
    if (!confirm('确定清空所有对话历史吗？此操作不可恢复！')) return
    try {
      await clearChatHistory()
      setHistoryList([])
    } catch (err) {
      alert('清空失败: ' + err.message)
    }
  }

  // 从历史记录中加载对话
  function loadConversationFromHistory(conv) {
    const { metadata } = conv
    if (metadata && metadata.userMessage && metadata.botResponse) {
      setMessages([
        { from:'bot', text:'👋 您好！我是 AI 智能助手，这是您之前的对话记录。' },
        { from: 'user', text: metadata.userMessage },
        { from: 'bot', text: metadata.botResponse }
      ])
      setCurrentConversationId(conv.id)
    }
  }

  // 创建新对话
  function startNewConversation() {
    setMessages([
      { from:'bot', text:'👋 您好！我是 AI 智能助手，可以帮您：\n\n✨ 自然语言检索图片\n🔍 分析缺陷类型\n💡 提供专业建议\n🧠 记住对话历史，智能上下文理解\n\n试试输入："查找裂纹" 或 "显示所有油污图片"' }
    ])
    setCurrentConversationId(null)
  }

  // 页面加载时自动加载历史记录
  useEffect(() => {
    loadHistory(false) // 确保是刷新模式
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dateFilter])

  const quickActions = [
    { icon: '🔍', label: '查找裂纹', query: '查找裂纹' },
    { icon: '🛢️', label: '显示油污', query: '显示所有油污图片' },
    { icon: '📊', label: '统计分析', query: '统计各类缺陷数量' },
    { icon: '💡', label: '检测建议', query: '如何提高检测准确率' },
  ]

  return (
    <>
      <div className="site-bg bg-core" aria-hidden="true" />

      <div className="page-bg">
        <Header />
        <div className="chat-layout">
          {/* 左侧边栏 */}
          <div className={`chat-sidebar ${showSidebar ? 'show' : 'hide'}`}>
            <div className="sidebar-header">
              <button 
                className="new-chat-btn"
                onClick={startNewConversation}
                title="新建对话"
              >
                ➕ 新对话
              </button>
              <button 
                className="toggle-sidebar-btn"
                onClick={() => setShowSidebar(false)}
                title="收起侧边栏"
              >
                ◀
              </button>
            </div>

            {/* 新增：日期筛选 */}
            <div className="sidebar-filters">
              <select 
                value={dateFilter} 
                onChange={e => handleDateFilterChange(e.target.value)}
                className="date-filter-select"
              >
                <option value="all">📅 全部时间</option>
                <option value="today">📆 今天</option>
                <option value="yesterday">📆 昨天</option>
                <option value="week">📅 最近7天</option>
                <option value="month">📅 最近30天</option>
                <option value="year">📅 今年</option>
              </select>
            </div>

            <div className="sidebar-search">
              <input
                type="text"
                placeholder="🔍 搜索历史..."
                value={historySearchQuery}
                onChange={e => setHistorySearchQuery(e.target.value)}
                onKeyPress={e => e.key === 'Enter' && handleHistorySearch()}
              />
            </div>

            <div className="sidebar-list">
              {historyLoading && historyList.length === 0 ? (
                <div className="sidebar-loading">
                  <div className="loading-spinner"></div>
                  <span>加载中...</span>
                </div>
              ) : historyList.length === 0 ? (
                <div className="sidebar-empty">
                  <div className="empty-icon">💭</div>
                  <p className="empty-text">暂无聊天记录</p>
                  <p className="empty-hint">开始对话后会显示在这里</p>
                </div>
              ) : (
                <>
                  {historyList.map(conv => (
                    <div 
                      key={conv.id} 
                      className={`sidebar-item ${currentConversationId === conv.id ? 'active' : ''}`}
                      onClick={() => loadConversationFromHistory(conv)}
                    >
                      <div className="sidebar-item-content">
                        <div className="sidebar-item-header">
                          <div className="sidebar-item-title">
                            {conv.metadata?.userMessage?.substring(0, 25) || '新对话'}
                            {conv.metadata?.userMessage?.length > 25 && '...'}
                          </div>
                          <div className="sidebar-item-time">
                            {conv.metadata?.timestamp ? new Date(conv.metadata.timestamp).toLocaleString('zh-CN', {
                              month: 'numeric',
                              day: 'numeric',
                              hour: '2-digit',
                              minute: '2-digit'
                            }) : ''}
                          </div>
                        </div>
                        <div className="sidebar-item-preview">
                          {conv.metadata?.botResponse?.substring(0, 45) || ''}
                          {conv.metadata?.botResponse?.length > 45 && '...'}
                        </div>
                      </div>
                      <button 
                        className="sidebar-item-delete"
                        onClick={(e) => {
                          e.stopPropagation()
                          handleDeleteHistory(conv.id)
                        }}
                        title="删除对话"
                      >
                        ✕
                      </button>
                    </div>
                  ))}
                  
                  {/* 加载更多按钮 */}
                  {hasMoreHistory && (
                    <button 
                      className="load-more-btn"
                      onClick={loadMoreHistory}
                      disabled={historyLoading}
                    >
                      {historyLoading ? '⏳ 加载中...' : '📥 加载更多'}
                    </button>
                  )}
                </>
              )}
            </div>

            <div className="sidebar-footer">
              <button 
                onClick={() => loadHistory(false)}
                disabled={historyLoading}
                className="sidebar-action-btn"
              >
                🔄 刷新
              </button>
              <button 
                onClick={handleClearHistory}
                className="sidebar-action-btn danger"
              >
                🗑️ 清空
              </button>
            </div>
          </div>

          {/* 主聊天区域 */}
          <div className="chat-main">
            {!showSidebar && (
              <button 
                className="expand-sidebar-btn"
                onClick={() => setShowSidebar(true)}
                title="展开侧边栏"
              >
                ▶
              </button>
            )}

            <div className="chat-container">
              <div className="chat-header-main">
                <div>
                  <h2 className="page-title">💬 AI 智能助手</h2>
                  <p className="page-subtitle">自然语言检索 · 缺陷分析 · 专业建议 · 智能记忆</p>
                </div>
                <div className="chat-status">
                  <span className="status-dot"></span>
                  <span className="status-text">在线</span>
                </div>
              </div>

              {messages.length === 1 && !currentConversationId && (
                <div className="quick-actions">
                  <p className="quick-title">🚀 快速开始</p>
                  <div className="quick-buttons">
                    {quickActions.map((action, i) => (
                      <button 
                        key={i}
                        className="quick-btn"
                        onClick={() => {
                          setInput(action.query)
                          setTimeout(() => onSend(), 100)
                        }}
                      >
                        <span className="quick-icon">{action.icon}</span>
                        <span className="quick-label">{action.label}</span>
                      </button>
                    ))}
                  </div>
                </div>
              )}

              <div className="card chat-card">
                <div ref={scrollRef} className="chat-window" role="log">
                  {messages.map((m,i)=>(
                    <div key={i} className={`message-wrapper ${m.from}`}>
                      <div className={`message ${m.from} ${m.error ? 'error' : ''}`}>
                        <div className="message-avatar">
                          {m.from === 'user' ? '👤' : '🤖'}
                        </div>

                        <div className="message-content">
                          {m.text && (
                            <div className="message-bubble">
                              <div className="message-text">{m.text}</div>
                              <div className="message-time">
                                {new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}
                              </div>
                            </div>
                          )}

                          {m.structured && (
                            <div className="structured-card">
                              {m.structured.possibilities && (
                                <div className="struct-section">
                                  <div 
                                    className="struct-header"
                                    onClick={()=>setExpandedSections(prev=>({ ...prev, possibilities: !prev.possibilities }))}
                                  >
                                    <div className="struct-title">
                                      <span className="struct-icon">🎯</span>
                                      <strong>可能缺陷</strong>
                                      <span className="struct-badge">{m.structured.possibilities.length}</span>
                                    </div>
                                    <span className="struct-toggle">
                                      {expandedSections.possibilities ? '▲' : '▼'}
                                    </span>
                                  </div>
                                  {expandedSections.possibilities && (
                                    <div className="struct-content">
                                      {m.structured.possibilities.map((p,idx)=>{
                                        const risk = mapConfidenceToRisk(p.confidence)
                                        return (
                                          <div key={idx} className="defect-item">
                                            <div className="defect-header">
                                              <span className="defect-name">{p.name}</span>
                                              <span className={`risk-pill ${risk.label.toLowerCase()}`}>
                                                {risk.label}
                                              </span>
                                            </div>
                                            <div className="defect-reason">{p.reason}</div>
                                            {p.confidence && (
                                              <div className="defect-confidence">
                                                置信度: {p.confidence}
                                              </div>
                                            )}
                                          </div>
                                        )
                                      })}
                                    </div>
                                  )}
                                </div>
                              )}

                              {m.structured.checks && (
                                <div className="struct-section">
                                  <div 
                                    className="struct-header"
                                    onClick={()=>setExpandedSections(prev=>({ ...prev, checks: !prev.checks }))}
                                  >
                                    <div className="struct-title">
                                      <span className="struct-icon">✅</span>
                                      <strong>建议检查</strong>
                                      <span className="struct-badge">{m.structured.checks.length}</span>
                                    </div>
                                    <span className="struct-toggle">
                                      {expandedSections.checks ? '▲' : '▼'}
                                    </span>
                                  </div>
                                  {expandedSections.checks && (
                                    <div className="struct-content">
                                      {m.structured.checks.map((c,idx)=>(
                                        <div key={idx} className="check-item">
                                          <div className="check-title">{c.title}</div>
                                          <ul className="check-steps">
                                            {c.steps.map((step, si) => (
                                              <li key={si}>{step}</li>
                                            ))}
                                          </ul>
                                        </div>
                                      ))}
                                    </div>
                                  )}
                                </div>
                              )}

                              {m.structured.uploadChecklist && (
                                <div className="struct-section">
                                  <div 
                                    className="struct-header"
                                    onClick={()=>setExpandedSections(prev=>({ ...prev, uploadChecklist: !prev.uploadChecklist }))}
                                  >
                                    <div className="struct-title">
                                      <span className="struct-icon">📋</span>
                                      <strong>上传清单</strong>
                                    </div>
                                    <span className="struct-toggle">
                                      {expandedSections.uploadChecklist ? '▲' : '▼'}
                                    </span>
                                  </div>
                                  {expandedSections.uploadChecklist && (
                                    <div className="struct-content">
                                      <div className="checklist">
                                        {m.structured.uploadChecklist.map((item, idx) => (
                                          <div key={idx} className="checklist-item">
                                            <span className="checklist-icon">📌</span>
                                            {item}
                                          </div>
                                        ))}
                                      </div>
                                    </div>
                                  )}
                                </div>
                              )}

                              {m.structured.searchKeywords && (
                                <div className="struct-section">
                                  <div 
                                    className="struct-header"
                                    onClick={()=>setExpandedSections(prev=>({ ...prev, searchKeywords: !prev.searchKeywords }))}
                                  >
                                    <div className="struct-title">
                                      <span className="struct-icon">🔑</span>
                                      <strong>推荐关键词</strong>
                                    </div>
                                    <span className="struct-toggle">
                                      {expandedSections.searchKeywords ? '▲' : '▼'}
                                    </span>
                                  </div>
                                  {expandedSections.searchKeywords && (
                                    <div className="struct-content">
                                      <div className="keywords">
                                        {m.structured.searchKeywords.map((kw, idx) => (
                                          <span key={idx} className="keyword-tag">{kw}</span>
                                        ))}
                                      </div>
                                    </div>
                                  )}
                                </div>
                              )}
                            </div>
                          )}

                          {m.images && m.images.length > 0 && (
                            <div className="images-grid">
                              {m.images.map((img, idx) => (
                                <div key={idx} className="image-item">
                                  <img src={img.dataUrl} alt={img.name} />
                                  <div className="image-overlay">
                                    <div className="image-name">{img.name}</div>
                                    {img.detections && img.detections.length > 0 && (
                                      <div className="image-tags">
                                        {img.detections.slice(0, 2).map((d, di) => {
                                          const cls = d.class || d.label || d.type || '未知'
                                          const risk = mapConfidenceToRisk(d.confidence)
                                          return (
                                            <span key={di} className={`img-tag ${risk.label.toLowerCase()}`}>
                                              {cls}
                                            </span>
                                          )
                                        })}
                                      </div>
                                    )}
                                  </div>
                                </div>
                              ))}
                            </div>
                          )}

                          {m.img && (
                            <div className="single-image">
                              <img src={m.img} alt="" />
                            </div>
                          )}

                          {m.detections && m.detections.length > 0 && (
                            <div className="detection-tags">
                              {m.detections.map((d,idx)=>{
                                const cls = d.class || d.label || d.type || '未知'
                                const conf = (typeof d.confidence === 'number') ? d.confidence : null
                                const risk = mapConfidenceToRisk(conf)
                                return (
                                  <div key={idx} className="detection-tag">
                                    <span className="tag-name">{cls}</span>
                                    <span className={`tag-risk ${risk.label.toLowerCase()}`}>{risk.label}</span>
                                    {conf != null && (
                                      <span className="tag-conf">{Math.round(conf*100)}%</span>
                                    )}
                                  </div>
                                )
                              })}
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}

                  {isTyping && (
                    <div className="message-wrapper bot">
                      <div className="message bot">
                        <div className="message-avatar">🤖</div>
                        <div className="message-content">
                          <div className="typing-indicator">
                            <span></span>
                            <span></span>
                            <span></span>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </div>

                <div className="chat-input-area">
                  <div className="input-wrapper">
                    <input 
                      ref={inputRef}
                      className="chat-input" 
                      value={input} 
                      onChange={e=>setInput(e.target.value)}
                      onKeyPress={handleKeyPress}
                      placeholder="输入消息... (按 Enter 发送)" 
                      disabled={loading}
                    />
                    <button 
                      className="send-btn" 
                      onClick={onSend} 
                      disabled={loading || !input.trim()}
                    >
                      {loading ? '⏳' : '🚀'}
                    </button>
                  </div>
                  <div className="input-footer">
                    <label className="chat-mode-toggle">
                      <input 
                        type="checkbox" 
                        checked={chatOnly} 
                        onChange={e=>setChatOnly(e.target.checked)} 
                      />
                      <span>仅聊天模式（不检索图片）</span>
                    </label>
                    <div className="input-hint">💡 支持自然语言查询</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  )
}